package com.example.localmusic;


import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.util.ArrayList;
import java.util.List;

public class PermissionUtils {
    private static PermissionUtils permissionUtils;
    private final int mRequestCode = 100; // 权限请求码
    private onPermissionCallbackListener mListener;
    private PermissionUtils(){}

    public interface onPermissionCallbackListener{
        void onGranted();
        void onDenied(List<String> deniedPermissions);
    }

    public static PermissionUtils getInstance(){
        if (permissionUtils == null){
            synchronized (PermissionUtils.class){
                if (permissionUtils == null){
                    permissionUtils = new PermissionUtils();
                }
            }
        }
        return permissionUtils;
    }

    public void onRequestPermission(Activity context, String []permissions, onPermissionCallbackListener listener){
        mListener = listener;
        //        判断手机版本 6.0以上需要申请权限
        if (Build.VERSION.SDK_INT >= 23) {
//            创建一个集合，放没有授予的权限
            List<String>mPermissionList = new ArrayList<>();
            for (int i = 0; i < permissions.length; i++){
                int res = ContextCompat.checkSelfPermission(context, permissions[i]);
                if (res != PackageManager.PERMISSION_GRANTED) {
                    mPermissionList.add(permissions[i]);
                }
            }

//            申请权限
            if (mPermissionList.size() > 0) {
                String[] permission_arr = mPermissionList.toArray(new String[mPermissionList.size()]);
                ActivityCompat.requestPermissions(context, permission_arr,mRequestCode);
            }else {
                // 说明权限都通过，可以做想做的事
                mListener.onGranted();
            }
        }
    }


    public void onRequestPermissionsResult(Activity context, int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == mRequestCode){
            List<String> deniedPermissions = new ArrayList<>();
            if (grantResults.length > 0){
                for (int i = 0; i< grantResults.length ; i++){
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        deniedPermissions.add(permissions[i]);
                    }
                }
            }
            if (deniedPermissions.size() == 0) {
                mListener.onGranted();
            }else {
                mListener.onDenied(deniedPermissions);
            }
        }else {
            mListener.onGranted();
        }
    }


}
